﻿using System;
using System.Collections.Generic;

namespace ETModel
{
    /// <summary>
    /// Actor消息会话管理组件
    /// </summary>
	public class ActorMessageSenderComponent: Component
	{
        /// <summary>  
        ///  角色ID的（geta服务器与map服务器之间的会话）的ActorMessageSender的映射
        /// </summary>
		public readonly Dictionary<long, ActorMessageSender> ActorMessageSenders = new Dictionary<long, ActorMessageSender>();

		public override void Dispose()
		{
			if (this.IsDisposed)
			{
				return;
			}
			base.Dispose();
			foreach (ActorMessageSender actorMessageSender in this.ActorMessageSenders.Values)
			{
				actorMessageSender.Dispose();
			}
			this.ActorMessageSenders.Clear();
		}

        /// <summary>
        /// 根据ID 从字典得到一个会话ActorMessageSender 如果没有会新建
        /// </summary>
        /// <param name="id">角色ID 会根据这个冲位置服务器得到服务器ID</param>
        /// <returns></returns>
		public ActorMessageSender Get(long id)
		{
			if (id == 0)
			{
				throw new Exception($"actor id is 0");
			}
			if (this.ActorMessageSenders.TryGetValue(id, out ActorMessageSender actorMessageSender))
			{
				return actorMessageSender;
			}
            //这里没有指定actorId 那么在初始化ActorMessageSender 会从位置服务器查找actorIdID 对其赋值
            actorMessageSender = ComponentFactory.CreateWithId<ActorMessageSender>(id);
			actorMessageSender.Parent = this;
			this.ActorMessageSenders[id] = actorMessageSender;
			return actorMessageSender;
		}

        /// <summary>
        /// 根据actorId 从字典得到一个会话ActorMessageSender 如果没有会新建
        /// </summary>
        /// <param name="actorId">服务器ID</param>
        /// <returns></returns>
        public ActorMessageSender GetWithActorId(long actorId)
		{
			if (actorId == 0)
			{
				throw new Exception($"actor id is 0");
			}
			if (this.ActorMessageSenders.TryGetValue(actorId, out ActorMessageSender actorMessageSender))
			{
				return actorMessageSender;
			}
            //这里在创建的时候就指定了actorId 那么在初始化ActorMessageSender  不需要再从位置服务器查找actorIdID
            actorMessageSender = ComponentFactory.CreateWithId<ActorMessageSender, long>(actorId, actorId); 
            actorMessageSender.Parent = this;
			this.ActorMessageSenders[actorId] = actorMessageSender;
			return actorMessageSender;
		}

        //移除
		public void Remove(long id)
		{
			ActorMessageSender actorMessageSender;
			if (!this.ActorMessageSenders.TryGetValue(id, out actorMessageSender))
			{
				return;
			}
			this.ActorMessageSenders.Remove(id);
			actorMessageSender.Dispose();
		}
	}
}
